using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace CS490_Capstone___Stubby.Page
{
    public partial class Administrator : System.Web.UI.Page
    {
        // Global variables
        WebServiceApplication.WebService webService = new WebServiceApplication.WebService();
        List<_Venue> venueList = new List<_Venue>();
        List<_Section> sectionList = new List<_Section>();
        List<_Ticket> ticketList = new List<_Ticket>();
        List<_OpenEvent> eventList = new List<_OpenEvent>();

        // Calls the recreateObjects() method to load dynamic objects before the postback.
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            // Create the Session variable to add more rows to the page on click.
            try
            {
                // Increment the row count to avoid ID confliction.
                int count = Convert.ToInt32(Session["insertEventRowCount"]);
                count++;
                Session["insertEventRowCount"] = count;
            }
            catch (NullReferenceException)
            {
                // The Session variable doesn't exist, so create it.
                Session.Add("insertEventRowCount", 0);
            }

            // Remove the controls from the parent object to avoid ViewState Exceptions.
            autoGeneratedContent.Controls.Clear();
            recreateObjects();
            recreateDirtyCode();
        }

        // Formats the page with custom sizing, styling, authentication, etc.
        protected void Page_Load(object sender, EventArgs e)
        {
            // Determine if the client is running JavaScript or not.
            // JSChecked -indicates if it tried to run the javascript version
            string path = Request.Url.ToString();

            if (Session["JSChecked"] == null)
            {
                // Prevent infinite loop
                Session["JSChecked"] = "Checked";
                Page.ClientScript.RegisterStartupScript(this.GetType(), "redirect", 
                    "window.location.href='" + path + "';", true);
            }

            if (path.Contains("height="))
            {
                // JavaScript is enabled.
                NoJavaScriptLabel.Text = "";
            }
            else
            {
                // JavaScript is disabled.
                NoJavaScriptLabel.Text = "NOTE: You currently have JavaScript disabled. In order to use " +
                    "the administrator page correctly, you must enable JavaScript. Please enable " +
                    "JavaScript and reload this page.";
            }

            // Check to make sure the user is correctly logged in. If not, redirect them to the login page.
            try
            {
                if (webService.getAdminSession(Session["AdminUserName"].ToString()) != Session.SessionID)
                    Response.Redirect("LogIn.aspx");
            }
            catch (NullReferenceException)
            {
                // The user tried to access the page without logging in.
                // Redirect to the login page.
                Session.Remove("autoRedirect");
                Session.Add("autoRedirect", "Administrator.aspx");
                Response.Redirect("LogIn.aspx");
            }

            String browserHeight;
            int contentHeight;

            // read screen height passed through URL
            if (Request.QueryString.ToString() != "")
            {
                HtmlGenericControl searchBody = (HtmlGenericControl)Page.Master.FindControl("myBody");
                // displays the appropriate header menu
                searchBody.Attributes.Add("onload", "showJavaScriptHeader();");

                // sets browser height to the visible browser height as passed by the query string
                // sets browser height to minimum of 550px if browser height is smaller
                browserHeight = (int.Parse(Request.QueryString["height"].ToString()) > 550) 
                    ? Request.QueryString["height"].ToString() : "550";
            }
            else
            {
                // sets browser height to default 800px if browser height cannot be determined
                browserHeight = "800";
            }

            // calculate and set the size of the input panel to fill the screen
            content.Height = contentHeight = int.Parse(browserHeight) - 120;
            topSpacer.Height = ((contentHeight - 220) / 2) - 15 > 0 ? ((contentHeight - 220) / 2) - 15 : 0;
        }

        // Recreates each dynamic object on the page.
        private void recreateObjects()
        {
            // RECREATE TICKET MODIFICATION OBJECTS.

                // Create an event list. During a delete the textboxes will be greyed out. 
                // During an update, the textboxes can be modified.
                // During an insert, there is only 1 row with a "add row" button.
                createEventListInPanel();
        }

        // Adds the list of event controls in the autoGeneratedPanel.
        private void createEventListInPanel()
        {
            // The insert row will only have one row.
            if (ddl_QueryType.SelectedValue == "DELETE")
            {
                // Create the select all checkbox.
                CheckBox checkBoxAll = new CheckBox();
                checkBoxAll.AutoPostBack = true;
                checkBoxAll.EnableViewState = true;
                checkBoxAll.CheckedChanged += new EventHandler(CheckChanged);
                checkBoxAll.ID = "checkBoxAll";
                autoGeneratedContent.Controls.Add(checkBoxAll);

                // Create the header Textboxes
                TextBox txtNameTitle = new TextBox();
                txtNameTitle.Width = 240;
                txtNameTitle.Enabled = false;
                txtNameTitle.Text = "Event Name";
                txtNameTitle.BackColor = System.Drawing.Color.Black;
                txtNameTitle.ForeColor = System.Drawing.Color.White;
                autoGeneratedContent.Controls.Add(txtNameTitle);

                TextBox txtAvailableTitle = new TextBox();
                txtAvailableTitle.Enabled = false;
                txtAvailableTitle.Text = "Is the Event Available?";
                txtAvailableTitle.BackColor = System.Drawing.Color.Black;
                txtAvailableTitle.ForeColor = System.Drawing.Color.White;
                autoGeneratedContent.Controls.Add(txtAvailableTitle);

                // add a line break after the control.
                autoGeneratedContent.Controls.Add(new LiteralControl("<br />"));

                // Populate the events below the header textboxes.
                foreach (_OpenEvent OE in webService.getAllEvents())
                {
                    // Create a checkbox for each event.
                    CheckBox cb = new CheckBox();
                    cb.Checked = false;
                    cb.ID = OE.eventName;
                    autoGeneratedContent.Controls.Add(cb);

                    // Create a textbox (disabled for delete statements) populated with event data.
                    TextBox txtName = new TextBox();
                    txtName.ID = "Name" + OE.eventName;
                    txtName.Width = 240;
                    txtName.TextChanged += new EventHandler(TextChanged);
                    TextBox txtAvailable = new TextBox();
                    txtAvailable.ID = "Available" + OE.eventName;
                    txtAvailable.TextChanged += new EventHandler(TextChanged);

                    // Create labels used to notify the user that the fields were successfully updated.
                    Label lblNotification = new Label();
                    lblNotification.ID = "Notify" + OE.eventName;
                    lblNotification.Text = "";

                    // Disable the textboxes.
                    txtName.Enabled = false;
                    txtAvailable.Enabled = false;

                    // Add the event data into the textboxes.
                    txtName.Text = OE.eventName;
                    txtAvailable.Text = OE.eventAvailable.ToString();

                    // Disable ViewState on controls.
                    txtName.EnableViewState = false;
                    txtAvailable.EnableViewState = false;

                    // add the controls after the checkboxes.
                    autoGeneratedContent.Controls.Add(txtName);
                    autoGeneratedContent.Controls.Add(txtAvailable);
                    autoGeneratedContent.Controls.Add(lblNotification);

                    // add a line break after the control.
                    autoGeneratedContent.Controls.Add(new LiteralControl("<br />"));
                }
            }
            else if (ddl_QueryType.SelectedValue == "UPDATE")
            {
                // Create the header Textboxes
                TextBox txtNameTitle = new TextBox();
                txtNameTitle.Width = 240;
                txtNameTitle.Enabled = false;
                txtNameTitle.Text = "Event Name";
                txtNameTitle.BackColor = System.Drawing.Color.Black;
                txtNameTitle.ForeColor = System.Drawing.Color.White;
                autoGeneratedContent.Controls.Add(txtNameTitle);

                TextBox txtAvailableTitle = new TextBox();
                txtAvailableTitle.Width = 240;
                txtAvailableTitle.Enabled = false;
                txtAvailableTitle.Text = "Is the Event Available?";
                txtAvailableTitle.BackColor = System.Drawing.Color.Black;
                txtAvailableTitle.ForeColor = System.Drawing.Color.White;
                autoGeneratedContent.Controls.Add(txtAvailableTitle);

                // add a line break after the control.
                autoGeneratedContent.Controls.Add(new LiteralControl("<br />"));

                // Populate the events below the header textboxes.
                foreach (_OpenEvent OE in webService.getAllEvents())
                {
                    // Create a textbox populated with event data.
                    TextBox txtName = new TextBox();
                    txtName.ID = "Name" + OE.eventName;
                    txtName.Width = 240;
                    txtName.TextChanged += new EventHandler(TextChanged);
                    
                    DropDownList txtAvailable = new DropDownList();
                    txtAvailable.ID = "Available" + OE.eventName;
                    txtAvailable.Width = 240;
                    txtAvailable.Items.Add("TRUE");
                    txtAvailable.Items.Add("FALSE");
                    txtAvailable.SelectedValue = OE.eventAvailable.ToString().ToUpper();
                    txtAvailable.SelectedIndexChanged += new EventHandler(TextChanged);

                    // Create labels used to notify the user that the fields were successfully updated.
                    Label lblNotification = new Label();
                    lblNotification.ID = "Notify" + OE.eventName;
                    lblNotification.Text = "";

                    // Add the event data into the textboxes.
                    txtName.Text = OE.eventName;

                    // add the controls.
                    autoGeneratedContent.Controls.Add(txtName);
                    autoGeneratedContent.Controls.Add(txtAvailable);
                    /* Separate the boxes and the label with space. */
                    autoGeneratedContent.Controls.Add(new LiteralControl("&nbsp;&nbsp;&nbsp;")); 
                    autoGeneratedContent.Controls.Add(lblNotification);

                    // add a line break after the control.
                    autoGeneratedContent.Controls.Add(new LiteralControl("<br />"));
                }
            }
            else if (ddl_QueryType.SelectedValue == "INSERT")
            {
                // Create the header Textboxes
                TextBox txtNameTitle = new TextBox();
                txtNameTitle.Width = 240;
                txtNameTitle.Enabled = false;
                txtNameTitle.Text = "Event Name";
                txtNameTitle.BackColor = System.Drawing.Color.Black;
                txtNameTitle.ForeColor = System.Drawing.Color.White;
                autoGeneratedContent.Controls.Add(txtNameTitle);

                TextBox txtAvailableTitle = new TextBox();
                txtAvailableTitle.Width = 240;
                txtAvailableTitle.Enabled = false;
                txtAvailableTitle.Text = "Is the Event Available?";
                txtAvailableTitle.BackColor = System.Drawing.Color.Black;
                txtAvailableTitle.ForeColor = System.Drawing.Color.White;
                autoGeneratedContent.Controls.Add(txtAvailableTitle);

                // add a line break after the control.
                autoGeneratedContent.Controls.Add(new LiteralControl("<br />"));

                // Create blank textboxes to insert the new values into.
                TextBox txtNewTextBoxName = new TextBox();
                txtNewTextBoxName.ID = "newTextBoxName" + Session["insertEventRowCount"];
                txtNewTextBoxName.Width = 240;
                txtNewTextBoxName.Enabled = true;
                autoGeneratedContent.Controls.Add(txtNewTextBoxName);

                AjaxControlToolkit.TextBoxWatermarkExtender watermark = 
                    new AjaxControlToolkit.TextBoxWatermarkExtender();
                watermark.TargetControlID = "newTextBoxName" + Session["insertEventRowCount"];
                watermark.ID = "newTextBoxNameWatermark" + Session["insertEventRowCount"];
                watermark.WatermarkCssClass = "watermarked";
                watermark.WatermarkText = "Type Event Name...";
                watermark.EnableViewState = false;
                autoGeneratedContent.Controls.Add(watermark);

                DropDownList ddlAvailable = new DropDownList();
                ddlAvailable.ID = "ddlAvailable" + Session["insertEventRowCount"];
                ddlAvailable.Width = 240;
                ddlAvailable.Enabled = true;
                ddlAvailable.Items.Add("Select Availability");
                ddlAvailable.Items.Add("TRUE");
                ddlAvailable.Items.Add("FALSE");
                autoGeneratedContent.Controls.Add(ddlAvailable);

                // Create labels used to notify the user that the fields were successfully updated.
                Label lblNotification = new Label();
                lblNotification.ID = "Notify" + Session["insertEventRowCount"];
                lblNotification.Text = "";
            }
            else
            {
                // Do nothing. The selectedValue is QueryType.
            }
        }


        /* DROP DOWN BOX METHODS */
        protected void ddl_QueryType_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Clear the next dropdown boxes contents and re-add the title item along with the event names.
            ddl_Event.Items.Clear();
            ddl_Event.Items.Add("EVENT...");

            // For each Query Type excluding the title name, enable the next dropdown and populate its data.
            // Enable all drop down menus and buttons based on the selected value BEFORE the postback.
            if (ddl_QueryType.SelectedItem.Text != "Query Type")
            {
                // Disable all succeeding drop down boxes except the very next one.
                ddl_Venue.Enabled = false;
                ddl_Section.Enabled = false;
                ddl_Ticket.Enabled = false;

                // If only the query type object is enabled execute these objects.
                if (ddl_QueryType.Enabled == true && ddl_Event.Enabled == false)
                {
                    ddl_Event.SelectedValue = "EVENT...";
                }

                ddl_Venue.SelectedValue = "VENUE...";
                ddl_Section.SelectedValue = "SECTION...";
                ddl_Ticket.SelectedValue = "TICKET...";

                // enable the next dropdown box.
                ddl_Event.Enabled = true;
            }
            else
            {
                ddl_Event.SelectedValue = "EVENT...";
                ddl_Venue.SelectedValue = "VENUE...";
                ddl_Section.SelectedValue = "SECTION...";
                ddl_Ticket.SelectedValue = "TICKET...";

                // Disable all succeeding drop down boxes.
                ddl_Event.Enabled = false;
                ddl_Venue.Enabled = false;
                ddl_Section.Enabled = false;
                ddl_Ticket.Enabled = false;
            }

            // Set visibility of the insert, delete, and update buttons based on the selected item.
            if (ddl_QueryType.SelectedValue == "DELETE")
            {
                // Enable the modal popup for the DeleteButton
                ConfirmDeletePopup.Visible = true;

                btn_AddRowIntoAutoGeneratedObjects.Visible = false;
                btn_DeleteFromAutoGeneratedObjects.Visible = true;
                btn_InsertFromAutoGeneratedObjects.Visible = false;
                btn_UpdateFromAutoGeneratedObjects.Visible = false;
            }
            else if (ddl_QueryType.SelectedValue == "INSERT")
            {
                // Disable the modal popup for the DeleteButton
                ConfirmDeletePopup.Visible = false;

                btn_AddRowIntoAutoGeneratedObjects.Visible = true;
                btn_DeleteFromAutoGeneratedObjects.Visible = false;
                btn_InsertFromAutoGeneratedObjects.Visible = true;
                btn_UpdateFromAutoGeneratedObjects.Visible = false;
            }
            else if (ddl_QueryType.SelectedValue == "UPDATE")
            {
                // Disable the modal popup for the DeleteButton
                ConfirmDeletePopup.Visible = false;

                btn_AddRowIntoAutoGeneratedObjects.Visible = false; 
                btn_DeleteFromAutoGeneratedObjects.Visible = false;
                btn_InsertFromAutoGeneratedObjects.Visible = false;
                btn_UpdateFromAutoGeneratedObjects.Visible = true;
            }
            else
            {
                // Disable the modal popup for the DeleteButton
                ConfirmDeletePopup.Visible = false;

                btn_AddRowIntoAutoGeneratedObjects.Visible = false; 
                btn_DeleteFromAutoGeneratedObjects.Visible = false;
                btn_InsertFromAutoGeneratedObjects.Visible = false;
                btn_UpdateFromAutoGeneratedObjects.Visible = false;
            }

            // Populate the next dropdown box.
            foreach (_OpenEvent OE in webService.getAllEvents())
            {
                ddl_Event.Items.Add(OE.eventName);
            }
        }

        protected void ddl_Event_SelectedIndexChanged(object sender, EventArgs e)
        {
            // For each event name excluding the title name, enable the next dropdown and populate its data.
            if (ddl_Event.SelectedItem.Text != "EVENT...")
            {
                // Disable all succeeding drop down boxes except the very next one.
                ddl_Section.Enabled = false;
                ddl_Ticket.Enabled = false;

                // If the event object is enabled, and only the event object. execute these objects.
                if (ddl_Event.Enabled == true && ddl_Venue.Enabled == false)
                {
                    // Set the succeeding drop down boxes selected indexes to default.
                    ddl_Venue.SelectedValue = "VENUE...";
                }

                ddl_Section.SelectedValue = "SECTION...";
                ddl_Ticket.SelectedValue = "TICKET...";

                // enable the next dropdown box.
                ddl_Venue.Enabled = true;
            }
            else
            {
                // Disable all succeeding drop down boxes.
                ddl_Venue.Enabled = false;
                ddl_Section.Enabled = false;
                ddl_Ticket.Enabled = false;

                // Set the succeeding drop down boxes selected indexes to default.
                ddl_Venue.SelectedValue = "VENUE...";
                ddl_Section.SelectedValue = "SECTION...";
                ddl_Ticket.SelectedValue = "TICKET...";
            }

            // Clear the next dropdown boxes contents and re-add the title item along with the event names.
            ddl_Venue.Items.Clear();
            ddl_Venue.Items.Add("VENUE...");

            // Populate the next dropdown box.
            foreach (_Venue v in webService.getVenuesFromEvent(ddl_Event.SelectedValue))
            {
                ddl_Venue.Items.Add(v.venueName);
            }
        }

        protected void ddl_Venue_SelectedIndexChanged(object sender, EventArgs e)
        {
            // For each venue name excluding the title name, enable the next dropdown and populate its data.
            if (ddl_Venue.SelectedItem.Text != "VENUE...")
            {
                // Disable all succeeding drop down boxes except the very next one.
                ddl_Ticket.Enabled = false;

                // If the venue object is enabled, and only the venue object. execute these objects.
                if (ddl_Venue.Enabled == true && ddl_Section.Enabled == false)
                {
                    // Set the succeeding drop down boxes selected indexes to default.
                    ddl_Section.SelectedValue = "SECTION...";
                }

                ddl_Ticket.SelectedValue = "TICKET...";

                // enable the next dropdown box.
                ddl_Section.Enabled = true;
            }
            else
            {
                // Disable all succeeding drop down boxes.
                ddl_Section.Enabled = false;
                ddl_Ticket.Enabled = false;

                // Set the succeeding drop down boxes selected indexes to default.
                ddl_Section.SelectedValue = "SECTION...";
                ddl_Ticket.SelectedValue = "TICKET...";
            }

            // Clear the next dropdown boxes contents and re-add the title item along with the event names.
            ddl_Section.Items.Clear();
            ddl_Section.Items.Add("SECTION...");

            // Populate the next dropdown box.
            foreach (_Section s in 
                webService.getSectionsInVenue(ddl_Event.SelectedValue, ddl_Venue.SelectedValue))
            {
                ddl_Section.Items.Add(s.sectionName);
            }
        }

        protected void ddl_Section_SelectedIndexChanged(object sender, EventArgs e)
        {
            // For each section name excluding title name, enable the next dropdown and populate its data.
            if (ddl_Section.SelectedItem.Text != "SECTION...")
            {
                // If the section object is enabled, and only the section object. execute these objects.
                if (ddl_Section.Enabled == true && ddl_Ticket.Enabled == false)
                {
                    // Set the succeeding drop down boxes selected indexes to default.
                    ddl_Ticket.SelectedValue = "TICKET...";
                }

                // enable the next dropdown box.
                ddl_Ticket.Enabled = true;
            }
            else
            {
                // Disable all succeeding drop down boxes.
                ddl_Ticket.Enabled = false;

                // Set the succeeding drop down boxes selected indexes to default.
                ddl_Ticket.SelectedValue = "TICKET...";
            }

            // Clear the next dropdown boxes contents and re-add the title item along with the event names.
            ddl_Ticket.Items.Clear();
            ddl_Ticket.Items.Add("TICKET...");

            // Populate the next dropdown box.
            // Use a count object to create an ID for each unique ticket.
            int count = 0;
            foreach (_Ticket t in webService.getTicketsFromSection(ddl_Event.SelectedValue, 
                ddl_Venue.SelectedValue, ddl_Section.SelectedValue))
            {
                count++;
                ddl_Ticket.Items.Add(count.ToString());
            }
        }

        protected void ddl_Ticket_SelectedIndexChanged(object sender, EventArgs e)
        {
            // The recreateObjects() method will handle the population of data in the panel.
            // For each ticket name excluding  title name, enable the next dropdown and populate its data.
            if (ddl_Section.SelectedItem.Text != "TICKET...")
            {
            }
            else
            {
                // DO NOTHING.
            }
        }


        /* QUERY BUTTON METHODS */
        protected void btn_DeleteFromAutoGeneratedObjects_Click(object sender, EventArgs e)
        {
            // This is the delete method for the events.
            if (ddl_Event.Enabled == true && ddl_Venue.Enabled == false)
            {
                // Run through each control in the autoGeneratedContent.
                foreach (Control ctrl in autoGeneratedContent.Controls)
                {
                    // If the control is a checkbox implement the following code.
                    if (ctrl is CheckBox)
                    {
                        // For each checkbox  checked, execute a delete statement using the control's ID.
                        // The control's ID should be the eventName (should be the deleteEvent parameter).
                        CheckBox cb = (CheckBox)ctrl;
                        if (cb.ID != "checkBoxAll")
                        {
                            if (cb.Checked == true)
                            {
                                int code = webService.deleteEvent(cb.ID);

                                // Update label text for the updated textbox with results from the database.
                                switch (code)
                                {
                                    case 0:
                                    // Run through each control in the autoGeneratedContent.
                                    foreach (Control newCtrl in autoGeneratedContent.Controls)
                                    {
                                        if (newCtrl is Label)
                                        {
                                            Label lbl = (Label)newCtrl;

                                            // Add the new text if the name matches.
                                            if (lbl.ID == "Notify" + cb.ID)
                                            {
                                                lbl.Text = "Deleted!";
                                            }
                                        }
                                    }
                                    break;
                                    case 1:
                                    // Run through each control in the autoGeneratedContent.
                                    foreach (Control newCtrl in autoGeneratedContent.Controls)
                                    {
                                        if (newCtrl is Label)
                                        {
                                            Label lbl = (Label)newCtrl;

                                            // Add the new text if the name matches.
                                            if (lbl.ID == "Notify" + cb.ID)
                                            {
                                                lbl.Text = "Failed delete. There was an unknown error.";
                                            }
                                        }
                                    }
                                    break;
                                    case 2:
                                    // Run through each control in the autoGeneratedContent.
                                    foreach (Control newCtrl in autoGeneratedContent.Controls)
                                    {
                                        if (newCtrl is Label)
                                        {
                                            Label lbl = (Label)newCtrl;

                                            // Add the new text if the name matches.
                                            if (lbl.ID == "Notify" + cb.ID)
                                            {
                                                lbl.Text = "Failed. Unknown SQL Exception.";
                                            }
                                        }
                                    }
                                    break;
                                    case 3:
                                    // Run through each control in the autoGeneratedContent.
                                    foreach (Control newCtrl in autoGeneratedContent.Controls)
                                    {
                                        if (newCtrl is Label)
                                        {
                                            Label lbl = (Label)newCtrl;

                                            // Add the new text if the name matches.
                                            if (lbl.ID == "Notify" + cb.ID)
                                            {
                                                lbl.Text = "Failed. Event name should be less than " +
                                                    "50 characters.";
                                            }
                                        }
                                    }
                                    break;
                                    case 4:
                                    // Run through each control in the autoGeneratedContent.
                                    foreach (Control newCtrl in autoGeneratedContent.Controls)
                                    {
                                        if (newCtrl is Label)
                                        {
                                            Label lbl = (Label)newCtrl;

                                            // Add the new text if the name matches.
                                            if (lbl.ID == "Notify" + cb.ID)
                                            {
                                                lbl.Text = "Failed. Event name already exists.";
                                            }
                                        }
                                    }
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            // This is the delete method for the venues.
            else if (ddl_Venue.Enabled == true && ddl_Section.Enabled == false)
            {
            }
            // This is the delete method for the sections.
            else if (ddl_Section.Enabled == true && ddl_Ticket.Enabled == false)
            {
            }
            // This is the delete method for the tickets.
            else
            {
            }
        }

        protected void btn_InsertFromAutoGeneratedObjects_Click(object sender, EventArgs e)
        {
            string eventName = "";
            bool available = false;

            // Run through each control in the autoGeneratedContent.
            foreach (Control ctrl in autoGeneratedContent.Controls)
            {
                // Extract the name of the event.
                if (ctrl is TextBox)
                {
                    TextBox txt = (TextBox)ctrl;
                    try
                    {
                        if (txt.ID.Contains("newTextBoxName"))
                        {
                            eventName = txt.Text;
                        }
                    }
                    catch (NullReferenceException) { }
                }

                // Extract the availability of the event.
                if (ctrl is DropDownList)
                {
                    DropDownList ddl = (DropDownList)ctrl;
                    if (ddl.ID.Contains("ddlAvailable"))
                    {
                        available = Convert.ToBoolean(ddl.SelectedValue);
                    }
                }

                // Insert the record and set the label text.
                if (ctrl is Label)
                {
                    Label lbl = (Label)ctrl;
                    int code = webService.insertEvent(eventName, available);

                    // Update label text for the updated textbox with results from the database.
                    switch (code)
                    {
                        case 0:
                            // Add the new text if the name matches.
                            if (lbl.ID.Contains("Notify"))
                            {
                                lbl.Text = "Inserted!";
                            }
                            break;
                        case 1:
                            // Add the new text if the name matches.
                            if (lbl.ID.Contains("Notify"))
                            {
                                lbl.Text = "Failed insert. There was an unknown error.";
                            }
                            break;
                        case 2:
                            // Add the new text if the name matches.
                            if (lbl.ID.Contains("Notify"))
                            {
                                lbl.Text = "Failed. Unknown SQL Exception.";
                            }
                            break;
                        case 3:
                            // Add the new text if the name matches.
                            if (lbl.ID.Contains("Notify"))
                            {
                                lbl.Text = "Failed. Event name should be less than 50 characters.";
                            }
                            break;
                        case 4:
                            // Add the new text if the name matches.
                            if (lbl.ID.Contains("Notify"))
                            {
                                lbl.Text = "Failed. Event name already exists.";
                            }
                            break;
                    }
                }
            }
        }

        protected void btn_UpdateFromAutoGeneratedObjects_Click(object sender, EventArgs e)
        {

        }

        protected void btn_AddRowIntoAutoGeneratedObjects_Click(object sender, EventArgs e)
        {
            int count = Convert.ToInt32(Session["insertEventRowCount"]);
            count++;
            Session["insertEventRowCount"] = count;
            autoGeneratedContent.Controls.Add(new LiteralControl("<br />"));
            
            // Create blank textboxes to insert the new values into.
            TextBox txtNewTextBoxName = new TextBox();
            txtNewTextBoxName.ID = "newTextBoxName" + Session["insertEventRowCount"];
            txtNewTextBoxName.Width = 240;
            txtNewTextBoxName.Enabled = true;
            autoGeneratedContent.Controls.Add(txtNewTextBoxName);

            AjaxControlToolkit.TextBoxWatermarkExtender watermark = 
                new AjaxControlToolkit.TextBoxWatermarkExtender();
            watermark.TargetControlID = "newTextBoxName" + Session["insertEventRowCount"];
            watermark.ID = "newTextBoxNameWatermark" + Session["insertEventRowCount"];
            watermark.WatermarkCssClass = "watermarked";
            watermark.WatermarkText = "Type Event Name...";
            watermark.EnableViewState = false;
            autoGeneratedContent.Controls.Add(watermark);

            DropDownList ddlAvailable = new DropDownList();
            ddlAvailable.ID = "ddlAvailable" + Session["insertEventRowCount"];
            ddlAvailable.Width = 240;
            ddlAvailable.Enabled = true;
            ddlAvailable.Items.Add("Select Availability");
            ddlAvailable.SelectedValue = "Select Availability";
            ddlAvailable.Items.Add("TRUE");
            ddlAvailable.Items.Add("FALSE");
            autoGeneratedContent.Controls.Add(ddlAvailable);

            // Create labels used to notify the user that the fields were successfully updated.
            Label lblNotification = new Label();
            lblNotification.ID = "Notify" + Session["insertEventRowCount"];
            lblNotification.Text = "";
        }


        /* CUSTOM EVENTS */
        protected void CheckChanged(object sender, EventArgs e)
        {
            // Run through each control in the autoGeneratedContent.
            foreach (Control ctrl in autoGeneratedContent.Controls)
            {
                // If the control is a checkbox implement the following code.
                if (ctrl is CheckBox)
                {
                    // For each checkbox checked, execute a delete statement using the control's ID.
                    // The control's ID should be the eventName.
                    CheckBox cb = (CheckBox)ctrl;
                    if (cb.ID == "checkBoxAll")
                    {
                        // Check all Checkbox values to match the CheckBoxAll value.
                        foreach (Control newCtrl in autoGeneratedContent.Controls)
                        {
                            if (newCtrl is CheckBox)
                            {
                                // Switch the checkbox values.
                                CheckBox switchCheckBox = (CheckBox)newCtrl;
                                if (cb.Checked == true)
                                {
                                    switchCheckBox.Checked = true;
                                }
                                else
                                {
                                    switchCheckBox.Checked = false;
                                }
                            }
                        }
                    }
                    else return;
                }
            }
        }

        protected void TextChanged(object sender, EventArgs e)
        {
            if (ddl_QueryType.SelectedValue != "UPDATE")
                return;

            dynamic temp = null;
            if (sender is TextBox)
            {
                temp = (TextBox)sender;
            }
            else if (sender is DropDownList)
            {
                temp = (DropDownList)sender;
            }

            string str = "";
            string eventName = "";
            bool available = false;

            if (temp.ID.StartsWith("Name"))
            {
                str = temp.ID.Remove(0, 4);
            }
            else if (temp.ID.StartsWith("Available"))
            {
                str = temp.ID.Remove(0, 9);
            }
            else
            {
                // Something went wrong.
            }

            // Run through each control in the autoGeneratedContent.
            foreach (Control ctrl in autoGeneratedContent.Controls)
            {
                if (ctrl is TextBox)
                {
                    try
                    {
                        TextBox txt = (TextBox)ctrl;
                        if (txt.ID.StartsWith("Name") && txt.ID.EndsWith(str))
                        {
                            eventName = txt.Text;
                        }
                    }
                    catch (NullReferenceException) { }
                }

                if (ctrl is DropDownList)
                {
                    DropDownList ddl = (DropDownList)ctrl;
                    if (ddl.ID.StartsWith("Available") && ddl.ID.EndsWith(str))
                    {
                        available = Convert.ToBoolean(ddl.SelectedValue);
                    }
                }
            }

            // Compare the old event name to the new event name. 
            // If they match, do not validate against the database.
            int comparison = eventName.CompareTo(str);
            int code; /* Use for switch statement. This is the returned code of the webservice method. */

            if (comparison == 0)
            {
                code = webService.updateEventWithoutValidation(str, eventName, available);
            }
            else
            {
                code = webService.updateEvent(str, eventName, available);
            }

            // Update the label text for the updated textbox based on the results from the database.
            switch (code)
            {
                case 0:
                // Run through each control in the autoGeneratedContent.
                foreach (Control ctrl in autoGeneratedContent.Controls)
                {
                    if (ctrl is Label)
                    {
                        Label lbl = (Label)ctrl;

                        // Add the new text if the name matches.                        
                        if (lbl.ID == "Notify" + str)
                        {
                            lbl.Text = "Updated!";
                        }
                    }
                }
                break;
                case 1:
                // Run through each control in the autoGeneratedContent.
                foreach (Control ctrl in autoGeneratedContent.Controls)
                {
                    if (ctrl is Label)
                    {
                        Label lbl = (Label)ctrl;

                        // Add the new text if the name matches.
                        if (lbl.ID == "Notify" + str)
                        {
                            lbl.Text = "Failed update. There was an unknown error.";
                        }
                    }
                }
                break;
                case 2:
                // Run through each control in the autoGeneratedContent.
                foreach (Control ctrl in autoGeneratedContent.Controls)
                {
                    if (ctrl is Label)
                    {
                        Label lbl = (Label)ctrl;

                        // Add the new text if the name matches.
                        if (lbl.ID == "Notify" + str)
                        {
                            lbl.Text = "Failed. Unknown SQL Exception.";
                        }
                    }
                }
                break;
                case 3:
                // Run through each control in the autoGeneratedContent.
                foreach (Control ctrl in autoGeneratedContent.Controls)
                {
                    if (ctrl is Label)
                    {
                        Label lbl = (Label)ctrl;

                        // Add the new text if the name matches.
                        if (lbl.ID == "Notify" + str)
                        {
                            lbl.Text = "Failed. Event name should be less than 50 characters.";
                        }
                    }
                }
                break;
                case 4:
                // Run through each control in the autoGeneratedContent.
                foreach (Control ctrl in autoGeneratedContent.Controls)
                {
                    if (ctrl is Label)
                    {
                        Label lbl = (Label)ctrl;

                        // Add the new text if the name matches.
                        if (lbl.ID == "Notify" + str)
                        {
                            lbl.Text = "Failed. Event name already exists.";
                        }
                    }
                }
                break;
            }
        }

        /* DIRTY CODE */
        private void recreateDirtyCode()
        {
            Button insertEvent = new Button();
            insertEvent.Click += new EventHandler(insertEventMethod);
            insertEvent.Text = "Click to Insert MyNewEvent Event";
            DirtyCodePlaceHolder.Controls.Add(insertEvent);
            DirtyCodePlaceHolder.Controls.Add(new LiteralControl("<br />"));

            Button updateEvent = new Button();
            updateEvent.Click += new EventHandler(updateEventMethod);
            updateEvent.Text = "Click to Update MyNewEvent to MyNewEventName & false";
            DirtyCodePlaceHolder.Controls.Add(updateEvent);
            DirtyCodePlaceHolder.Controls.Add(new LiteralControl("<br />"));

            Button deleteEvent = new Button();
            deleteEvent.Click += new EventHandler(deleteEventMethod);
            deleteEvent.Text = "Click to Delete MyNewEventName";
            DirtyCodePlaceHolder.Controls.Add(deleteEvent);
            DirtyCodePlaceHolder.Controls.Add(new LiteralControl("<br />"));

            Button insertVenue = new Button();
            insertVenue.Click += new EventHandler(insertVenueMethod);
            insertVenue.Text = "Click to insert venue myNewVenue into Test Event 3";
            DirtyCodePlaceHolder.Controls.Add(insertVenue);
            DirtyCodePlaceHolder.Controls.Add(new LiteralControl("<br />"));

            Button updateVenue = new Button();
            updateVenue.Click += new EventHandler(updateVenueMethod);
            updateVenue.Text = "Click to update venue myNewVenue into updatedVenue";
            DirtyCodePlaceHolder.Controls.Add(updateVenue);
            DirtyCodePlaceHolder.Controls.Add(new LiteralControl("<br />"));

            Button deleteVenue = new Button();
            deleteVenue.Click += new EventHandler(deleteVenueMethod);
            deleteVenue.Text = "Click to delete venue updatedVenue from Test Event 3";
            DirtyCodePlaceHolder.Controls.Add(deleteVenue);
            DirtyCodePlaceHolder.Controls.Add(new LiteralControl("<br />"));
        }

        protected void insertEventMethod(object sender, EventArgs e)
        {
            webService.insertEvent("MyNewEvent", true);
        }

        protected void updateEventMethod(object sender, EventArgs e)
        {
            webService.updateEvent("MyNewEvent", "MyNewEventName", false);
        }

        protected void deleteEventMethod(object sender, EventArgs e)
        {
            webService.deleteEvent("MyNewEventName");
        }

        protected void insertVenueMethod(object sender, EventArgs e)
        {
            webService.insertVenue("myNewVenue", DateTime.Now, DateTime.Today, true, "Test Event 3", "Seattle", "WA");
        }

        protected void updateVenueMethod(object sender, EventArgs e)
        {
            webService.updateVenue("Test Event 3", "myNewVenue", "updateVenue", DateTime.Now, DateTime.Today, false, "Renton", "WA");
        }

        protected void deleteVenueMethod(object sender, EventArgs e)
        {
            webService.deleteVenue("Test Event 3", "updatedVenue");
        }
    }
}